/*
 * net_util.c
 *
 *  Created on: May 13, 2016
 *      Author: root
 */

#include "net_util.h"
#include "log.h"
#include   <stdio.h>
#include   <sys/ioctl.h>
#include   <sys/socket.h>
#include   <netinet/in.h>
#include   <net/if.h>
#include   <string.h>
#include "str_util.h"

void get_mac(char* mac, char* ethname){
	struct ifreq ifreq;
	int sock;
	if((sock=socket(AF_INET,SOCK_STREAM,0)) <0){
		LogStr("get_mac()--->socket error!\n");
		return;
	}
	strcpy(ifreq.ifr_name, ethname);
	if(ioctl(sock,SIOCGIFHWADDR,&ifreq) <0){
		LogStr("get_mac()--->ioctl error!\n");
		return;
	}

	sprintf(mac, "%02x:%02x:%02x:%02x:%02x:%02x",
	            (unsigned   char)ifreq.ifr_hwaddr.sa_data[0],
	            (unsigned   char)ifreq.ifr_hwaddr.sa_data[1],
	            (unsigned   char)ifreq.ifr_hwaddr.sa_data[2],
	            (unsigned   char)ifreq.ifr_hwaddr.sa_data[3],
	            (unsigned   char)ifreq.ifr_hwaddr.sa_data[4],
	            (unsigned   char)ifreq.ifr_hwaddr.sa_data[5]);
	Log("the mac address is %s\n", mac);
}


void remove_colon_of_mac(char* o_mac, char* n_mac){
	if(strlen(o_mac) != 17){
		return;
	}
	int offset = 0;
	int i;
	pstr_copy(n_mac, offset, o_mac, 0, 2);
	offset+=2;
	for(i = 0; i < 5; i++){
		pstr_copy(n_mac, offset, o_mac, (i + 1)*3, 2);
		offset+=2;
	}
	pstr_copy(n_mac, offset, "", 0, 1);
}
